define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var newhouse_id = Fast.api.query('newhouse_id');
    var structure_id = Fast.api.query('structure_id');

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'newhouse/building/index' + location.search,
                    add_url: 'newhouse/building/add',
                    edit_url: 'newhouse/building/edit/structure_id/'+structure_id,
                    del_url: 'newhouse/building/del',
                    multi_url: 'newhouse/building/multi',
                    dragsort_url: 'ajax/weigh',
                    table: 'newhouse_building',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                escape: false,
                pagination: false,
                commonSearch: false,
                search: false,
                columns: [
                    [
                        {field: 'title', title: __('Title'), align: 'left'},
                        {field: 'flag', title: __('Flag'), searchList: {"0":__('Flag 0'),"1":__('Flag 1')}, formatter: Controller.api.formatter.flag},
                        {field: 'admin.nickname', title: __('Admin.nickname')},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, buttons: [
                                {
                                    name: 'lq',
                                    text: '添加楼/区',
                                    icon: 'fa fa-building',
                                    classname: 'btn btn-xs btn-default btn-dialog',
                                    url: function (row, column) {
                                        return "newhouse/building/add?newhouse_id=" + newhouse_id + "&structure_id=" + structure_id + "&pid=" + row.id;
                                    },
                                    visible: function (row) {
                                        if (row.pid == 0) {
                                            return true;
                                        }
                                    }
                                }, {
                                    name: 'hx',
                                    text: '添加户型',
                                    icon: 'fa fa-image',
                                    classname: 'btn btn-xs btn-default btn-addtabs',
                                    url: function (row, column) {
                                        return "newhouse/layout?newhouse_id=" + newhouse_id + "&structure_id=" + structure_id + "&building_id=" + row.id;
                                    },
                                    visible: function (row) {
                                        if (row.pid > 0) {
                                            return true;
                                        }
                                    }
                                }], events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            var parenttable = table.closest('.bootstrap-table');
            var options = table.bootstrapTable('getOptions');
            var toolbar = $(options.toolbar, parenttable);
            $(toolbar).off('click', Table.config.addbtn);
            $(toolbar).on('click', Table.config.addbtn, function () {
                var ids = Table.api.selectedids(table);
                var url = options.extend.add_url;
                if (url.indexOf("{ids}") !== -1) {
                    url = Table.api.replaceurl(url, {ids: ids.length > 0 ? ids.join(",") : 0}, table);
                }
                if (newhouse_id !== null) {
                    url = url + '?newhouse_id=' + newhouse_id + '&structure_id=' + structure_id;
                }
                Fast.api.open(url, __('Add'), $(this).data() || {});
            });
        },
        add: function () {
            if (newhouse_id) {
                $('#c-newhouse_id').val(newhouse_id);
            }
            if (structure_id) {
                $('#c-structure_id').val(structure_id);
            }
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));

                var image_input = $('#plupload-image').data("input-id") ? $('#plupload-image').data("input-id") : "";
                var image_preview = $('#plupload-image').data("preview-id") ? $('#plupload-image').data("preview-id") : "";
                if (image_preview) {
                    $(document.body).off("click", "#" + image_preview + " .btn-trash");
                    // 监听事件
                    $("#plupload-image").data("upload-success", function(data, ret) {
                        //这里进行后续操作
                        $(this).hide();
                    });
                    // 移除按钮事件
                    $(document.body).on("click", "#" + image_preview + " .btn-trash", function () {
                        var that = $(this);
                        var path = $("#" + image_preview + " [data-url]");
                        Layer.confirm('是否删除该图片？（删除后不可恢复）',
                            {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
                            function (index) {
                                var options = {
                                    url: 'newhouse/structure/delUpload',
                                    data: {
                                        bid: $("#plupload-image").data('bid'),
                                        dbfield: $("#plupload-image").data('field'),
                                        path: path.data("url")
                                    }
                                }
                                Fast.api.ajax(options, function () {
                                    $("#" + image_input).val('');
                                    that.closest("li").remove();
                                    $("#plupload-image").show();
                                    Layer.close(index);
                                });
                            }
                        );
                    });
                }
                if ($("#" + image_input).val() != '') {
                    $("#" + image_input).hide();
                }

                var form = $("form[role=form]");
                if ($(".fieldlists", form).size() > 0) {
                    require(['template'], function (Template) {
                        //刷新隐藏textarea的值
                        var refresh = function (name) {
                            var data = {};
                            var textarea = $("textarea[name='" + name + "']", form);
                            var container = textarea.closest("dl");
                            var template = container.data("template");
                            $.each($("input,select,textarea", container).serializeArray(), function (i, j) {
                                var reg = /\[(\w+)\]\[(\w+)\]$/g;
                                var match = reg.exec(j.name);
                                if (!match)
                                    return true;
                                match[1] = "x" + parseInt(match[1]);
                                if (typeof data[match[1]] == 'undefined') {
                                    data[match[1]] = {};
                                }
                                data[match[1]][match[2]] = j.value;
                            });
                            var result = template ? [] : {};
                            $.each(data, function (i, j) {
                                if (j) {
                                    if (!template) {
                                        if (j.key != '') {
                                            result[j.key] = j.value;
                                        }
                                    } else {
                                        result.push(j);
                                    }
                                }
                            });
                            textarea.val(JSON.stringify(result));
                        };
                        //监听文本框改变事件
                        $(document).on('change keyup', ".fieldlists input,.fieldlists textarea,.fieldlists select", function () {
                            refresh($(this).closest("dl").data("name"));
                        });
                        //追加控制
                        $(".fieldlists", form).on("click", ".btn-append,.append", function (e, row) {
                            var container = $(this).closest("dl");
                            var index = container.data("index");
                            var name = container.data("name");
                            var template = container.data("template");
                            var data = container.data();
                            index = index ? parseInt(index) : 0;
                            container.data("index", index + 1);
                            var row = row ? row : {};
                            var vars = {index: index, name: name, data: data, row: row};
                            var html = Template.render(template, vars);
                            $(html).insertBefore($(this).closest("dd"));
                            $(this).trigger("fa.event.appendfieldlist", $(this).closest("dd").prev());
                        });
                        //移除控制
                        $(".fieldlists", form).on("click", "dd .btn-remove", function () {
                            var container = $(this).closest("dl");
                            $(this).closest("dd").remove();
                            refresh(container.data("name"));
                        });
                        //渲染数据
                        $(".fieldlists", form).each(function () {
                            var container = this;
                            var textarea = $("textarea[name='" + $(this).data("name") + "']", form);
                            if (textarea.val() == '') {
                                return true;
                            }
                            var template = $(this).data("template");
                            var json = {};
                            try {
                                json = JSON.parse(textarea.val());
                            } catch (e) {
                            }
                            $.each(json, function (i, j) {
                                $(".btn-append,.append", container).trigger('click', template ? j : {
                                    key: i
                                });
                            });
                        });
                    });
                }
            },
            formatter: {
                flag: function (value, row, index) {
                    return '<a class="btn-change text-success" data-url="'+$.fn.bootstrapTable.defaults.extend.multi_url+'" data-id="' + row.id + '" data-params="flag=' + (row.flag == '0' ? '1' : '0') + '"><i class="fa ' + (row.flag == '0' ? 'fa-toggle-off' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                }
            }
        }
    };
    return Controller;
});
